package com.jianjun.framework.web.interceptor;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.StrUtil;
import com.jfinal.aop.Inject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.ThreadPoolKit;
import com.jianjun.common.constant.HttpStatus;
import com.jianjun.framework.manager.factory.AsyncFactory;
import com.jianjun.framework.security.LoginUser;
import com.jianjun.framework.security.service.TokenService;
import com.jianjun.framework.web.domain.AjaxResult;

import java.util.Objects;


/**
 * token过滤器 验证token有效性
 * @author Source
 */

public class JwtAuthenticationTokenInterceptor implements Interceptor {
    static ThreadLocal<LoginUser> TL_USER = new ThreadLocal<>();

    @Inject
    TokenService tokenService;

    public static LoginUser getLoginUser() {
        return TL_USER.get();
    }


    @Override
    public void intercept(Invocation inv) {
        TimeInterval timer = DateUtil.timer();
        LoginUser loginUser = tokenService.getLoginUser(CORSGlobalInterceptor.getRequest());
        if (Objects.nonNull(loginUser)) {
            tokenService.verifyToken(loginUser);
            TL_USER.set(loginUser);
            inv.invoke();
        } else {
            int code = HttpStatus.UNAUTHORIZED;
            String msg = StrUtil.format("请求访问：{}，认证失败，无法访问系统资源", CORSGlobalInterceptor.getRequest().getRequestURI());
            inv.getController().renderJson(JsonKit.toJson(AjaxResult.error(code, msg)));
            ThreadPoolKit.execute(AsyncFactory.recordOper(inv, timer, new Exception("认证失败，无法访问系统资源")));
        }
    }
}
